// ListCtrlData.cpp : implementation file
//

#include "stdafx.h"
#include "ListCtrlData.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CListCtrlData

CListCtrlData::CListCtrlData()
	: m_iDefaultColWidth(50)
{
}

CListCtrlData::~CListCtrlData()
{
}


BEGIN_MESSAGE_MAP(CListCtrlData, CListCtrl)
	//{{AFX_MSG_MAP(CListCtrlData)
		// NOTE - the ClassWizard will add and remove mapping macros here.
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

void CListCtrlData::PreSubclassWindow() 
{
 	ModifyStyle( LVS_TYPEMASK, LVS_REPORT );
 	SetExtendedStyle( GetExtendedStyle() |LVS_EX_FULLROWSELECT |LVS_EX_GRIDLINES |LVS_EX_ONECLICKACTIVATE );

// Initialize columns
	const CCopyableArray<LVCOLUMN,LVCOLUMN&> &arrCols= m_itemdata.GetCols();
	for (int iCol= 0; iCol < arrCols.GetSize(); iCol++)
	{
		LVCOLUMN &lvc= arrCols[iCol];
		InsertColumn( lvc.iSubItem, &lvc );
// 		if (0 == lvc.iSubItem)
// 			SetColumn( lvc.iSubItem, &lvc );
	}

	SetColumnWidth();

	SetShownData();

	CListCtrl::PreSubclassWindow();
}

void CListCtrlData::SetShownData()
{
	LockWindowUpdate();

	if (GetItemCount() > 0)
		DeleteAllItems();

	for (int iItem= 0; iItem < m_itemdata.GetItemCount(); iItem++)
	{
		int iInserted= 0;
		for (int iSubItem= 0; iSubItem < m_itemdata.GetSubItemCount(); iSubItem++)
		{
			const CString &strSubItem = m_itemdata.GetSubItem( iItem, iSubItem );
			if (0 == iSubItem)
				iInserted = InsertItem( 0, strSubItem );
			else
				SetItemText( iInserted, iSubItem, strSubItem );
		}
	}

	UnlockWindowUpdate();
}

void CListCtrlData::SetColumnWidth()
{
	CArray<LVCOLUMN,LVCOLUMN&> arrAlterableLvcs;
	int iUsedWidth= 0;
		const int iGridlindWidth= 1;
		const CCopyableArray<LVCOLUMN,LVCOLUMN&> &arrCols= m_itemdata.GetCols();
		for (int iCol= 0; iCol < arrCols.GetSize(); iCol++)
		{
			LVCOLUMN &lvc= arrCols[iCol];
			if (lvc.cx <= 0)
				arrAlterableLvcs.Add( lvc );
			else
				iUsedWidth += lvc.cx + iGridlindWidth;
		}
// Set alterable columns
	if (arrAlterableLvcs.GetSize() > 0)
	{
		CRect rectListCtrl;
			GetWindowRect( &rectListCtrl );
		const int iLeftWidth = rectListCtrl.Width() - iGridlindWidth - iUsedWidth;
		int iEachWidth = iLeftWidth / arrAlterableLvcs.GetSize() - iGridlindWidth;
		for (int iAlterable= 0; iAlterable < arrAlterableLvcs.GetSize(); iAlterable++)
		{
			LVCOLUMN &lvc= arrAlterableLvcs[iAlterable];
				lvc.cx = (iEachWidth > m_iDefaultColWidth) ? iEachWidth : m_iDefaultColWidth;
			SetColumn( lvc.iSubItem, &lvc );
		}
	}
	
}
